<?php

namespace services\merchant;

use Yii;
use common\helpers\StringHelper;
use common\components\Service;
use common\models\merchant\SettleAccount;
use common\models\forms\MerchantCreditsLogForm;
use yii\web\UnprocessableEntityHttpException;

/**
 * Class SettleAccountService
 * @package services\merchant
 * @author YiiFrame <21931118@qq.com>
 */
class SettleAccountService extends Service
{
    /**
     * @return array|\yii\db\ActiveRecord[]
     */
    public function settleAccounts()
    {
        $data = Yii::$app->services->merchantSettleAccountRecords->settleAccounts();
        foreach ($data as $datum) {
            $model = new SettleAccount();
            $model->attributes = $datum;
            $model->serial_number = date('YmdHi') . StringHelper::random(10, true);
            $model->start_time = $this->lastRecordByMerchantId($model->merchant_id);
            $model->end_time = time();
            if (!$model->save()) {
                throw new UnprocessableEntityHttpException($this->getError($model));
            }

            if ($model->merchant_money > 0) {
                Yii::$app->services->merchantCreditsLog->incrMoney(new MerchantCreditsLogForm([
                    'merchant' => Yii::$app->services->merchant->findById($model->merchant_id),
                    'num' => $model->merchant_money,
                    'map_id' => $model->id,
                    'pay_type' => 0,
                    'credit_group' => 'all',
                    'remark' => '统一结算,结算单号：' . $model->serial_number,
                ]));
            } else {
                Yii::$app->services->merchantCreditsLog->decrMoney(new MerchantCreditsLogForm([
                    'merchant' => Yii::$app->services->merchant->findById($model->merchant_id),
                    'num' => $model->merchant_money,
                    'map_id' => $model->id,
                    'pay_type' => 0,
                    'credit_group' => 'all',
                    'remark' => '统一结算,结算单号：' . $model->serial_number,
                ]));
            }

            Yii::$app->services->merchantSettleAccountRecords->issueByMerchantId($model->merchant_id, $model->id, $model->serial_number);
        }
    }

    /**
     * 上次日期
     *
     * @param $merchant_id
     * @return false|int|string
     */
    public function lastRecordByMerchantId($merchant_id)
    {
        $time = SettleAccount::find()
            ->select(['end_time'])
            ->where(['merchant_id' => $merchant_id])
            ->orderBy('id desc')
            ->scalar();

        return !empty($time) ? $time : 0;
    }
}